//
//  onCache.swift
//  XNetwork_Example
//
//  Created by x on 2024/8/9.
//  Copyright © 2024 CocoaPods. All rights reserved.
//

import Moya
import RxSwift

public struct OnCache<Target: TargetType, C: Codable>
where Target: Cacheable, Target.ResponseType == Moya.Response {
    
    public let target: Target
    
    private let keyPath: String?
    
    private let decoder: JSONDecoder
    
    public init(target: Target, keyPath: String?, decoder: JSONDecoder) {
        self.target = target
        self.keyPath = keyPath
        self.decoder = decoder
    }
    // .OnCache() 里面调用此函数
    public func request() -> Single<C> {
        // 调用 Rx+TargetType 里面的request， 并将请求结果response缓存
        return target.requset().storeCachedResponse(for: target).map(C.self, atKeyPath: keyPath, using: decoder)
    }
}
